package com.kedacom.freedomLabel.view.activity.setting;

import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;

import com.kedacom.freedomLabel.R;
import com.kedacom.freedomLabel.base.BaseActivity;
import com.kedacom.freedomLabel.databinding.ActivitySettingSettingBinding;
import com.kedacom.freedomLabel.view.fragment.SettingFragmentsControl;
import com.kedacom.freedomLabel.view.fragment.setting.ASettingFragment;
import com.kedacom.freedomLabel.view.fragment.setting.BasicInformationFragment;
import com.kedacom.freedomLabel.view.fragment.setting.CommunicationSettingFragment;
import com.kedacom.freedomLabel.view.fragment.setting.CorrectionSettingFragment;
import com.kedacom.freedomLabel.view.fragment.setting.IDWriteBlockFragment;
import com.kedacom.freedomLabel.view.fragment.setting.NoScalesSettingFragment;
import com.kedacom.freedomLabel.view.fragment.setting.OperationSettingFragment;
import com.kedacom.freedomLabel.view.fragment.setting.OperatorControlSettingFragment;
import com.kedacom.freedomLabel.view.fragment.setting.ScalesSettingFragment;
import com.kedacom.freedomLabel.view.fragment.setting.SerialPortComFragment;
import com.kedacom.freedomLabel.view.fragment.setting.SerialPortFragment;
import com.kedacom.freedomLabel.view.fragment.setting.SystemSettingFragment;
import com.kedacom.freedomLabel.view.fragment.setting.UserInformationFragment;
import com.kedacom.freedomLabel.view.fragment.setting.WeightSettingFragment;
import com.kedacom.freedomLabel.viewmodel.setting.SettingViewModel;
import com.kedacom.lego.annotation.ContentView;
import com.kedacom.lego.annotation.ViewModel;
import com.seray.scaleviewlib.utils.LogUtils;


@ContentView(R.layout.activity_setting_setting)
@ViewModel(SettingViewModel.class)
public class SettingActivity extends BaseActivity<ActivitySettingSettingBinding, SettingViewModel>
        implements SettingFragmentsControl.ChildSettingFragmentClickCallback {

    FragmentManager mFragmentManager;
    String mLastTopChildFragmentTitle = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mFragmentManager = getSupportFragmentManager();
        ASettingFragment fragment = new BasicInformationFragment();
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        transaction.add(R.id.setting_item_container, fragment);
        mLastTopChildFragmentTitle = fragment.getFragmentTitle();
        mBinding.settingItemTitle.setText(mLastTopChildFragmentTitle);
        transaction.commit();
        initCheckedChangeListener();
    }

    // 返回
    public void onBackButtonClick(View view) {
        beep();
        finish();
    }

    private void initCheckedChangeListener() {


        try{
            int childCount = mBinding.settingMainGroup.getChildCount();
            for (int i = 0; i < childCount; i++) {
                mBinding.settingMainGroup.getChildAt(i).setOnClickListener(v -> beep());
            }
            mBinding.settingMainGroup.setOnCheckedChangeListener((group, checkedId) -> {
                FragmentTransaction transaction = mFragmentManager.beginTransaction();
                ASettingFragment openFragment = null;
                ScalesSettingFragment  weightFragment =null;
                OperatorControlSettingFragment operatorControlSettingFragment=null;
                switch (checkedId) {
                    case R.id.button_basic:
                        weightFragment=null;
                        operatorControlSettingFragment=null;
                        openFragment = new BasicInformationFragment();
                        break;
                    case R.id.button_system:
                        weightFragment=null;
                        operatorControlSettingFragment=null;
                        openFragment = new SystemSettingFragment();
                        break;
                    case R.id.button_weight:
                        openFragment=null;
                        operatorControlSettingFragment=null;
                        weightFragment = new ScalesSettingFragment();
                        break;
                    case R.id.button_operation:
                        weightFragment=null;
                        operatorControlSettingFragment=new  OperatorControlSettingFragment();
//                    openFragment = new OperationSettingFragment();
                        break;
                    case R.id.button_correction:
                        weightFragment=null;
                        operatorControlSettingFragment=null;
                        openFragment = new CorrectionSettingFragment();
                        break;
                    case R.id.button_communication:
                        weightFragment=null;
                        operatorControlSettingFragment=null;
                        openFragment = new CommunicationSettingFragment();
                        break;
                    case R.id.button_writecardblock:
                        weightFragment=null;
                        operatorControlSettingFragment=null;
                        openFragment = new IDWriteBlockFragment();
                        break;
                    case R.id.reboot_app:
                        DialogRestartApp("秤的一些频繁设置操作，必须重启App才可以生效");
                        break;
                    default:
                        openFragment = null;
                        break;
                }

                //这个操作是覆盖原来的fragment
                android.app.FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();

                if (openFragment != null) {
                    transaction.replace(R.id.setting_item_container, openFragment);
                    mLastTopChildFragmentTitle = openFragment.getFragmentTitle();
                    mBinding.settingItemTitle.setText(mLastTopChildFragmentTitle);
                    transaction.commit();
                }else if(weightFragment!=null){
                    //获取显示头的操作只能这么写
                    ASettingFragment aSettingFragment = new WeightSettingFragment();
                    transaction.replace(R.id.setting_item_container,aSettingFragment);
                    mLastTopChildFragmentTitle = aSettingFragment.getFragmentTitle();
                    mBinding.settingItemTitle.setText(mLastTopChildFragmentTitle);
                    transaction.commit();

                    fragmentTransaction.replace(R.id.setting_item_container, weightFragment);
                    fragmentTransaction.commit();
                }else if(operatorControlSettingFragment!=null){

                    ASettingFragment operationSettingFragment = new OperationSettingFragment();
                    transaction.replace(R.id.setting_item_container,operationSettingFragment);
                    mLastTopChildFragmentTitle = operationSettingFragment.getFragmentTitle();
                    mBinding.settingItemTitle.setText(mLastTopChildFragmentTitle);
                    transaction.commit();

                    fragmentTransaction.replace(R.id.setting_item_container, operatorControlSettingFragment);
                    fragmentTransaction.commit();
                }



            });
        }catch (Exception e){
            LogUtils.d("settingError======="+e.toString());
            e.toString();
        }

    }

    public void DialogRestartApp(String showErr) {
        AlertDialog normalDialog =
                new AlertDialog.Builder(SettingActivity.this)
                        .setTitle("重启App:")
                        .setMessage(showErr)
                        .setPositiveButton("确定",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        try {
                                            restartApp(SettingActivity.this);
                                        }catch (Exception e){
                                            e.printStackTrace();
                                        }

                                    }
                                }).create();
//        normalDialog.setCanceledOnTouchOutside(false);
//        normalDialog.setCancelable(false);
        normalDialog.show();

    }

    /**
     * 重启app
     * @param context
     */
    public static void restartApp(Context context) {

//        ActivityManager manager =(ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
//        manager.restartPackage("com.kedacom.freedomLabel");

        final Intent intent = context.getPackageManager().getLaunchIntentForPackage("com.kedacom.freedomLabel");
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent restartIntent = PendingIntent.getActivity(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);
        AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent); // 1秒钟后重启应用
        System.exit(0);


//        Intent intent =context.getPackageManager()
//                .getLaunchIntentForPackage(context.getPackageName());
//        PendingIntent restartIntent = PendingIntent.getActivity(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);
//        AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
//        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent); // 1秒钟后重启应用
//        System.exit(0);
    }
    /**
     * 处理设置子类 ItemView点击事件
     *
     * @param intention 意图
     */
    @Override
    public void onChildSettingFragmentItemClick(SettingFragmentsControl.Intention intention) {
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        // 用户信息设置
        ASettingFragment fragment = null;
        if (intention == SettingFragmentsControl.Intention.OPEN_USER_INFORMATION) {
            fragment = new UserInformationFragment();
            transaction.replace(R.id.setting_item_container, fragment);
            transaction.addToBackStack(null);
            transaction.commit();
        }else if(intention == SettingFragmentsControl.Intention.OPEN_ALARM_SERIAL_TEST){
            fragment = new SerialPortFragment();
            transaction.replace(R.id.setting_item_container,fragment);
            transaction.addToBackStack(null);
            transaction.commit();
        } else if(intention == SettingFragmentsControl.Intention.OPEN_ALARM_SERIAL_TEST_COM){
            fragment = new SerialPortComFragment();
            transaction.replace(R.id.setting_item_container,fragment);
            transaction.addToBackStack(null);
            transaction.commit();
        }
        if (fragment != null) {
            mBinding.settingItemTitle.setText(fragment.getFragmentTitle());
        }

        mBinding.settingItemBack.setVisibility(View.VISIBLE);
        mBinding.settingItemBack.setOnClickListener(v -> {
            beep();
            v.setClickable(false);
            onBackPressed();
            v.setVisibility(View.INVISIBLE);
            mBinding.settingItemTitle.setText(mLastTopChildFragmentTitle);
        });
    }
}